package cn.edu.zknu.mita.controller;

import cn.edu.zknu.mita.model.FindMsg;
import cn.edu.zknu.mita.model.User;
import cn.edu.zknu.mita.service.IFindMsgService;
import cn.edu.zknu.mita.service.IFindWallService;
import cn.edu.zknu.mita.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by iwlnner on 2020/3/19.
 */
@Controller
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IFindMsgService findMsgService;
    @Autowired
    private IFindWallService findWallService;

    @RequestMapping(value = "/checkLogin",method = RequestMethod.POST)
    public String checkLogin(String key, String userName, String passWord, HttpSession session, Model model){
        User user = userService.checkLogin(userName, passWord);
        if (user!=null){
            session.setAttribute("USER_IN_SESSION",user);
            if(key!=null&&!"".equals(key)){
                return "redirect:/releaseInformation?key="+key;
            }
            return "redirect:/index";
        }
        model.addAttribute("key",key);
        model.addAttribute("errorMsg","用户名或密码错误");
        return "login";
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        session.removeAttribute("USER_IN_SESSION");
        return "redirect:/index";
    }

    @RequestMapping("/myRelease")
    public String myRelease(HttpSession session,Model model){
        User user = (User) session.getAttribute("USER_IN_SESSION");
        if(user!=null){
            List<FindMsg> findMsgs = findMsgService.listMyRelease(user.getId());
            model.addAttribute("msgs",findMsgs);
        }
        return "MyRelease";
    }

    @ResponseBody
    @RequestMapping(value = "/seekOut",method = RequestMethod.POST)
    public String seekOut(@RequestBody String str){
        ObjectMapper obj=new ObjectMapper();
        try{
            Map map=obj.readValue(str,Map.class);
            //System.out.println(map);
            Integer id=(Integer) map.get("id");
            findMsgService.deleteFindMsg(Long.valueOf(id));
            findWallService.deleteFindImg(Long.valueOf(id));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

}
